package com.guw.TestThread;

//不安全的买票
public class TestSyn1 {
}

class BuyTicket implements Runnable {
    private int tickets = 100;
    boolean flag = true;
    @Override
    public void run() {
        while (flag) {
            buy();
        }
    }

    //public void buy(){
    //加上synchronized之后,出票顺序就是正常的了
    public synchronized void buy() {
        if (tickets <= 0) {
            flag = false;
            return;
        }
        System.out.println(Thread.currentThread().getName() + "买了第" + tickets-- + "张票");
    }

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket, "A").start();
        new Thread(buyTicket, "B").start();
        new Thread(buyTicket, "C").start();
    }
}
